﻿using System;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;

namespace AChance.Bll.Func
{
    public static class BllSession
    {
        private static IMemoryCache _sessions = new MemoryCache(Options.Create(new MemoryCacheOptions()));
        public class Info
        {
            /// <summary>
            /// 状态信息
            /// </summary>
            public BllVar.StateInfo StateInfo { get; set; } = new BllVar.StateInfo();
            /// <summary>
            /// 最后一次请求信息
            /// </summary>
            public LastReqInfoClass LastReqInfo { get; set; } = new LastReqInfoClass();
            public class LastReqInfoClass
            {
                /// <summary>
                /// 时间
                /// </summary>
                public DateTime Time { get; set; } = DateTime.Now;
                /// <summary>
                /// 代码
                /// </summary>
                public string Code { get; set; } = string.Empty;
                /// <summary>
                /// 数据
                /// </summary>
                public string Data { get; set; } = string.Empty;
            }
        }
        /// <summary>
        /// 判断会话是否存在
        /// </summary>
        public static bool Exists(string session)
        {
            return _sessions.TryGetValue(session, out _);
        }
        /// <summary>
        /// 创建会话
        /// </summary>
        public static string Create(BllVar.StateInfo stateInfo)
        {
            string session = Guid.NewGuid().ToString();
            _sessions.Set(session,
                new Info { StateInfo = stateInfo },
                new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromHours(2)));
            return session;
        }
        /// <summary>
        /// 获取状态信息
        /// </summary>
        public static BllVar.StateInfo GetStateInfo(string session)
        {
            return _sessions.Get<Info>(session).StateInfo;
        }
        /// <summary>
        /// 更新最后一次请求信息
        /// </summary>
        public static bool UpdateLastReqInfo(string session, string code, string data, bool checkUpdateInterval = true, double minUpdateInterval = 500)
        {
            var info = _sessions.Get<Info>(session);
            if (checkUpdateInterval
                && (DateTime.Now - info.LastReqInfo.Time).TotalMilliseconds < minUpdateInterval
                && !code.Contains(BllTrans.Code.Type.GET)
                && info.LastReqInfo.Code.Equals(code)
                && info.LastReqInfo.Data.Equals(data))
                return false;
            info.LastReqInfo.Time = DateTime.Now;
            info.LastReqInfo.Code = code;
            info.LastReqInfo.Data = data;
            return true;
        }
    }
}
